<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Proxy实现 双向数据绑定</title>
</head>

<body>
    input1: <input id="doubleInput" placeholder="双向绑定数据" />
    <div>
        输入值: <span id="displayValue"></span>
    </div>
    input2: <input id="doubleInput2" placeholder="双向绑定数据" />
    <script>
        function observe(originObject, onChange) {
            return new Proxy(originObject, {
                get(target, propName, receiver) {
                    const currentValue = Reflect.get(target, propName, receiver)
                    if (typeof currentValue === 'object' && currentValue !== null) {
                        // 访问到get的时候 创建新的proxy 后续再访问别的属性 就能检测到了 (lazy) 区别于DefineProperty
                        return observe(currentValue,onChange)
                    }
                    return currentValue
                },

                set(target, propName, newValue, receiver) {
                    if (onChange) {
                        onChange(propName, newValue)
                    }
                    return Reflect.set(target, propName, newValue, receiver)
                },
            })
        }

        const doubleInput = document.querySelector('#doubleInput')
        const displayValue = document.querySelector('#displayValue')
        const doubleInput2 = document.querySelector('#doubleInput2')

        const inputInfo = observe({
            value: ''
        }, (changeKey, newValue) => {
            if (changeKey === 'value') {
                doubleInput.value = newValue
                doubleInput2.value = newValue
                displayValue.textContent = newValue
            }
        })

        doubleInput.addEventListener('input', (e) => {
            inputInfo.value = e.target.value
        })

        doubleInput2.addEventListener('input', (e) => {
            inputInfo.value = e.target.value
        })
    </script>
</body>

</html>